<template>
  <div class="product-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>商品档案管理</h2>
      <p>管理商品基础信息，包括商品编码、名称、规格、分类、价格等</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="商品编码">
            <el-input v-model="searchForm.productCode" placeholder="请输入商品编码" clearable />
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable />
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
              <el-option label="电子产品" value="electronics" />
              <el-option label="服装" value="clothing" />
              <el-option label="食品" value="food" />
              <el-option label="家居" value="home" />
              <el-option label="图书" value="books" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增商品
      </el-button>
      <el-button type="success" @click="handleBatchImport">
        <el-icon><Upload /></el-icon>
        批量导入
      </el-button>
      <el-button type="warning" @click="handleBatchExport">
        <el-icon><Download /></el-icon>
        批量导出
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="productCode" label="商品编码" width="120" sortable />
        <el-table-column prop="productName" label="商品名称" min-width="150" />
        <el-table-column prop="category" label="分类" width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)">{{ getCategoryLabel(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="purchasePrice" label="采购价" width="100" sortable>
          <template #default="{ row }">
            ¥{{ row.purchasePrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="salePrice" label="销售价" width="100" sortable>
          <template #default="{ row }">
            ¥{{ row.salePrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" sortable />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" sortable />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品详情/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="product-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品编码" prop="productCode">
              <el-input v-model="formData.productCode" :disabled="dialogMode === 'view'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="formData.productName" :disabled="dialogMode === 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品分类" prop="category">
              <el-select v-model="formData.category" :disabled="dialogMode === 'view'" style="width: 100%">
                <el-option label="电子产品" value="electronics" />
                <el-option label="服装" value="clothing" />
                <el-option label="食品" value="food" />
                <el-option label="家居" value="home" />
                <el-option label="图书" value="books" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="formData.specification" :disabled="dialogMode === 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="formData.unit" :disabled="dialogMode === 'view'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" :disabled="dialogMode === 'view'" style="width: 100%">
                <el-option label="启用" value="active" />
                <el-option label="禁用" value="inactive" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购价" prop="purchasePrice">
              <el-input-number
                v-model="formData.purchasePrice"
                :disabled="dialogMode === 'view'"
                :precision="2"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售价" prop="salePrice">
              <el-input-number
                v-model="formData.salePrice"
                :disabled="dialogMode === 'view'"
                :precision="2"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            :disabled="dialogMode === 'view'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogMode !== 'view'" type="primary" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Upload, Download, Delete } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogMode = ref('add') // add, edit, view
const selectedRows = ref([])
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  productCode: '',
  productName: '',
  category: '',
  status: ''
})

// 表单数据
const formData = reactive({
  id: null,
  productCode: '',
  productName: '',
  category: '',
  specification: '',
  unit: '',
  purchasePrice: 0,
  salePrice: 0,
  status: 'active',
  description: ''
})

// 表单验证规则
const formRules = {
  productCode: [
    { required: true, message: '请输入商品编码', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  purchasePrice: [
    { required: true, message: '请输入采购价', trigger: 'blur' }
  ],
  salePrice: [
    { required: true, message: '请输入销售价', trigger: 'blur' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 模拟数据
const mockData = [
  {
    id: 1,
    productCode: 'P001',
    productName: 'iPhone 15 Pro',
    category: 'electronics',
    specification: '256GB 深空黑色',
    unit: '台',
    purchasePrice: 8999.00,
    salePrice: 9999.00,
    stock: 50,
    status: 'active',
    description: '苹果最新旗舰手机',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    productCode: 'P002',
    productName: '华为 Mate 60 Pro',
    category: 'electronics',
    specification: '512GB 雅川青',
    unit: '台',
    purchasePrice: 6499.00,
    salePrice: 6999.00,
    stock: 30,
    status: 'active',
    description: '华为旗舰手机',
    createTime: '2024-01-16 14:20:00'
  },
  {
    id: 3,
    productCode: 'P003',
    productName: '优衣库基础T恤',
    category: 'clothing',
    specification: 'L码 白色',
    unit: '件',
    purchasePrice: 39.00,
    salePrice: 59.00,
    stock: 200,
    status: 'active',
    description: '100%纯棉基础款T恤',
    createTime: '2024-01-17 09:15:00'
  },
  {
    id: 4,
    productCode: 'P004',
    productName: '三只松鼠坚果礼盒',
    category: 'food',
    specification: '1.2kg 混合装',
    unit: '盒',
    purchasePrice: 89.00,
    salePrice: 128.00,
    stock: 80,
    status: 'active',
    description: '精选坚果组合装',
    createTime: '2024-01-18 16:45:00'
  },
  {
    id: 5,
    productCode: 'P005',
    productName: '宜家北欧风台灯',
    category: 'home',
    specification: '白色 LED',
    unit: '个',
    purchasePrice: 199.00,
    salePrice: 299.00,
    stock: 25,
    status: 'inactive',
    description: '简约北欧风格台灯',
    createTime: '2024-01-19 11:30:00'
  }
]

// 方法
const getCategoryType = (category) => {
  const types = {
    electronics: 'primary',
    clothing: 'success',
    food: 'warning',
    home: 'info',
    books: 'danger'
  }
  return types[category] || 'info'
}

const getCategoryLabel = (category) => {
  const labels = {
    electronics: '电子产品',
    clothing: '服装',
    food: '食品',
    home: '家居',
    books: '图书'
  }
  return labels[category] || category
}

const handleSearch = () => {
  loading.value = true
  // 模拟搜索
  setTimeout(() => {
    let filteredData = [...mockData]
    
    if (searchForm.productCode) {
      filteredData = filteredData.filter(item => 
        item.productCode.toLowerCase().includes(searchForm.productCode.toLowerCase())
      )
    }
    
    if (searchForm.productName) {
      filteredData = filteredData.filter(item => 
        item.productName.toLowerCase().includes(searchForm.productName.toLowerCase())
      )
    }
    
    if (searchForm.category) {
      filteredData = filteredData.filter(item => item.category === searchForm.category)
    }
    
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    
    tableData.value = filteredData
    pagination.total = filteredData.length
    loading.value = false
    
    ElMessage.success('搜索完成')
  }, 500)
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  loadData()
}

const handleAdd = () => {
  dialogMode.value = 'add'
  dialogTitle.value = '新增商品'
  resetFormData()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '编辑商品'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  dialogMode.value = 'view'
  dialogTitle.value = '查看商品详情'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除商品 "${row.productName}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的商品')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个商品吗？`,
    '确认批量删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟批量删除
    const selectedIds = selectedRows.value.map(row => row.id)
    tableData.value = tableData.value.filter(item => !selectedIds.includes(item.id))
    pagination.total -= selectedRows.value.length
    selectedRows.value = []
    ElMessage.success('批量删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleBatchImport = () => {
  ElMessage.info('批量导入功能开发中...')
}

const handleBatchExport = () => {
  ElMessage.info('批量导出功能开发中...')
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (dialogMode.value === 'add') {
        // 模拟新增
        const newProduct = {
          ...formData,
          id: Date.now(),
          stock: 0,
          createTime: new Date().toLocaleString()
        }
        tableData.value.unshift(newProduct)
        pagination.total++
        ElMessage.success('新增成功')
      } else if (dialogMode.value === 'edit') {
        // 模拟编辑
        const index = tableData.value.findIndex(item => item.id === formData.id)
        if (index > -1) {
          Object.assign(tableData.value[index], formData)
          ElMessage.success('编辑成功')
        }
      }
      dialogVisible.value = false
    }
  })
}

const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    productCode: '',
    productName: '',
    category: '',
    specification: '',
    unit: '',
    purchasePrice: 0,
    salePrice: 0,
    status: 'active',
    description: ''
  })
}

const loadData = () => {
  loading.value = true
  // 模拟加载数据
  setTimeout(() => {
    tableData.value = [...mockData]
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
}

.product-form {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-management {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .action-section {
    flex-direction: column;
  }
  
  .action-section .el-button {
    width: 100%;
  }
}
</style>